package com.itec471.deckapp;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

/**
 * The main activity. Displays screen for entering deck information
 *   and passes the input to other classes for calculations, then
 *   starts the output activity. If a plan has been previously saved,
 *   the user has the option of viewing the saved materials list.
 * @author ITEC-471 Grp2
 *
 */
public class MainActivity extends Activity {

	public final static String OUTPUT_MESSAGE = "com.itec471.deckcalculator.MESSAGE";
	public final static String TAG = "CalculatorMain";
	public ArrayList<String> results = new ArrayList<String>();
	private DeckModel deckModel;
	private Button mSavedData;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
    	super.onCreate(savedInstanceState);
    	setContentView(R.layout.activity_main);
    	
    	String[] fileArray = fileList();
    	
    	if(fileArray.length > 0)
    	{
        	mSavedData = (Button) findViewById(R.id.saved_data);
        	mSavedData.setVisibility(1);
    	}        
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
    
    
    /**
     *  The showSavedData method
     *  @param view
     */
    public void showSavedData(View view)
    {
    	String 
		strLine = "", 
		file = "materialsLists";
    	
    	// Create the intent for output
    	Intent intent = new Intent(this, DisplayMaterialsListActivity.class);
    	List<String> materialsList = new ArrayList<String>();
    	
    	// Get the deckModel instance
    	deckModel = DeckModel.getInstance();
    	
    	// Remove any previously calculated materials lists from the model
    	deckModel.setMaterialsList(new ArrayList<String>());
    	
    	try 
    	{   		
    		
			FileInputStream fis = this.openFileInput(file);
			InputStreamReader isr = new InputStreamReader(fis);
			// create BufferedReader to read file
			BufferedReader br = new BufferedReader(isr);
			
			strLine = br.readLine();
			
			// read file line by line to populate materialsList, set square feet string, set price string
			while(strLine != null)
			{				
				if (strLine.equals("area"))
				{
					strLine = br.readLine();
					deckModel.setSquareFeetString(strLine);
				}
				else if (strLine.equals("price"))
				{
					deckModel.setPriceString(br.readLine());
				}
				else
				{
					materialsList.add(strLine);
				}
				
				strLine = br.readLine();				
			}
		} 
		catch (FileNotFoundException e) 
		{
			String tag = "Reading Materials";
			Log.e(tag , "File not found");
		}
		catch (IOException e)
		{
			String tag = "Reading Materials";
			Log.e(tag, "IOException");
		}	
    	
    	results = new ArrayList<String>(); //reset results
    	
    	//List<String> mList = materialsList;    	
    	results.addAll(materialsList);
    	
    	// Pass the array to the the intent and start the activity
    	intent.putStringArrayListExtra(OUTPUT_MESSAGE, results);
    	startActivity(intent);    	
    }    
    
    
    
    
    /**
     *  Initiates calculations and output for the deck
     *   when the user clicks the 'calculate' button
     *  @param view
     */
    public void initiateCalc(View view){
    	double len = 0, width = 0, height = 0;
    	TextView message = (TextView)findViewById(R.id.has_input);
    	boolean hasInput = false;
    	
    	// Create the intent for output
    	Intent intent = new Intent(this, DisplayMaterialsListActivity.class);
    	
    	// Get the values input by user
    	EditText lenText = (EditText)findViewById(R.id.edit_length);
    	EditText widthText = (EditText)findViewById(R.id.edit_width);
    	EditText heightText = (EditText)findViewById(R.id.edit_height);
    	
    	// Convert string input to doubles. If nothing was input the 
    	//  value will be 0 and an error will be logged
    	try{
    		len = Double.valueOf(lenText.getText().toString());
    		width = Double.valueOf(widthText.getText().toString());
    		height = Double.valueOf(heightText.getText().toString());
    		if (len > 0 && width > 0 && height > 0){
    			hasInput = true;
    		}
    		else{
    			message.setText(R.string.invalid_measurements);
    		}
    	}
    	catch(Exception e){
    		Log.e(TAG, "Error converting input to double");
    		message.setText(R.string.missing_deck_info);
    	}   
    	
    	if (hasInput){
    		// Create the deck configuration
        	deckModel = DeckModel.getInstance(len, width, height);
        	
        	// Remove any previously calculated materials lists from the model
        	deckModel.setMaterialsList(new ArrayList<String>());
        	
        	// Set the type of decking
        	deckModel.setDeckingType(MaterialType.SPAN_RATED_DECKING);
        	
        	// Create a calculator and pass the asset manager for retrieving prices
        	MaterialsCalculator calc = new MaterialsCalculator(getAssets());
        	
        	results = new ArrayList<String>(); //reset results
        	
        	// Get the list of lumber and add to the output
        	List<String> temp = calc.calculateMaterials();
        	results.addAll(temp);
        	
        	// Pass the array to the the intent and start the activity
        	intent.putStringArrayListExtra(OUTPUT_MESSAGE, results);
        	startActivity(intent);
    	}    	
    }    
}
